import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TryLock {

    public static void main(String[] args) throws InterruptedException {
        var c = new  TaskQueuek();

        // get
        var t = new Thread(){
            public void run(){
                while(true){
                    try {
                        String r = c.getTask();
                        System.out.println("get => " + r);  
                        Thread.sleep(100); 
                    } catch(InterruptedException e) {}
                }
            }
        };
        t.start();
       

        // add 
        var Add = new Thread(()->{
            for(int j=0;j<10;j++){
                String ss = String.valueOf(j);
                System.out.println("add: "+ ss);
                c.addTask(ss);
                try { Thread.sleep(100); } catch(InterruptedException e) {}
            }    
        });
        Add.start();
        Add.join();
        Thread.sleep(100);
      
    }

}


class TaskQueuek {
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private Queue<String> queue = new LinkedList<>();

    public void addTask(String s) {
        lock.lock();
        try {
            queue.add(s);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public String getTask() throws InterruptedException{
        lock.lock();
        try {
            while (queue.isEmpty()) {
                condition.await();  // it's not a "wait"
            }
            return queue.remove();
        } finally {
            lock.unlock();
        }
    }
}
